﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SharpDND.Core;
using SharpDND.Core.Entity;
using SharpDND.Core.Entity.Common;
using SharpDNDTools.Forms.Core;
using SharpDNDTools.UserControls.Common;

namespace SharpDNDTools.UserControls.Core
{
    public partial class ucViewAlignments : UserControl
    {
        public ucViewAlignments()
        {
            InitializeComponent();

            LoadGrid();
        }

        private void LoadGrid()
        {
            Alignment alignment = new Alignment();
            List<Alignment> listOfAlignment = new List<Alignment>();

            foreach (SharpDNDBase baseObj in alignment.GetAll())
            {
                if (baseObj is Alignment)
                {
                    listOfAlignment.Add((Alignment) baseObj);
                }
            }

            ucMainViewer mainViewer = new ucMainViewer(new BindingSource {DataSource = listOfAlignment}) {Dock = DockStyle.Fill};

            mainViewer.OnAddButtonClicked -= mainViewer_OnAddButtonClicked;
            mainViewer.OnGridDoubleClicked -= mainViewer_OnGridDoubleClicked;
            mainViewer.OnItemSorted -= mainViewer_OnItemSorted;

            mainViewer.OnAddButtonClicked += mainViewer_OnAddButtonClicked;
            mainViewer.OnGridDoubleClicked += mainViewer_OnGridDoubleClicked;
            mainViewer.OnItemSorted += mainViewer_OnItemSorted;

            this.Controls.Clear();
            this.Controls.Add(mainViewer);

            this.Update();
        }

        private void mainViewer_OnItemSorted(object sender, EventArgs e)
        {
            foreach (Alignment alignment in ((List<Alignment>) ((BindingSource) sender).DataSource))
            {
                alignment.Save();
            }
        }

        private void mainViewer_OnGridDoubleClicked(object sender, EventArgs e)
        {
            Alignment alignment = new Alignment();
            frmAddEditAlignment frmMainEditor = new frmAddEditAlignment((Alignment) alignment.GetByID((Guid) sender));

            frmMainEditor.Closed -= frmMainEditor_Closed;
            frmMainEditor.Closed += frmMainEditor_Closed;

            frmMainEditor.ShowDialog();
        }

        private void frmMainEditor_Closed(object sender, EventArgs e)
        {
            if (((Form) sender).DialogResult == DialogResult.OK)
            {
                LoadGrid();
            }
        }

        private void mainViewer_OnAddButtonClicked(object sender, EventArgs e)
        {
            frmAddEditAlignment frmMainEditor = new frmAddEditAlignment(new Alignment());

            frmMainEditor.Closed -= frmMainEditor_Closed;
            frmMainEditor.Closed += frmMainEditor_Closed;

            frmMainEditor.ShowDialog();
        }
    }
}